package com.geyue.controller;

import com.geyue.common.toolbox.result.Res;
import com.geyue.core.model.Addr;
import com.geyue.core.model.City;
import com.geyue.core.service.AddrService;
import com.geyue.core.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Lyon on 2017/5/24.
 */
@Controller
@RequestMapping("/city")
public class CityController {

    @Autowired
    private CityService cityService;
    @Autowired
    private AddrService addrService;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(){
        return "city/list";
    }

    @RequestMapping(value = "/",method = RequestMethod.GET)
    @ResponseBody
    public Res list(Integer pageSize, Integer pageNum){
        return Res.success("",cityService.getPage(pageNum,pageSize,new City()));
    }

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(){
        return "city/add";
    }


    @RequestMapping(value = "/",method = RequestMethod.POST)
    @ResponseBody
    public Res add(City city){

        if(cityService.saveNotEmpty(city) > 0)
            return Res.success("添加成功!");

        return Res.fail("添加失败!");
    }

    @RequestMapping(value = "/edit/{id}",method = RequestMethod.GET)
    public String edit(@PathVariable Integer id, Model model){
        model.addAttribute("city",cityService.getOneByKey(id));
        return "city/edit";
    }

    @RequestMapping(value = "/",method = RequestMethod.PUT)
    @ResponseBody
    public Res edit(City city){

        if(cityService.updateNotEmpty(city) > 0)
            return Res.success("修改成功!");

        return Res.fail("修改失败!");
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public Res del(@PathVariable Integer id){

        if(cityService.deleteByKey(id) > 0){
            Addr addr = new Addr();
            addr.setCityId(id);
            if(addrService.delete(addr) > 0)
                return Res.success("删除成功!");
        }

        return Res.fail("删除失败!");
    }
}
